﻿using UnityEngine;
using System.Collections;
using DG.Tweening;
using Cinemachine;

public class DinosaurPkGame : BaseToyBoxGame
{

    private const string ASSET_PATH = "game_toybox/PkGameRoot";
    private const string SOUND_PATH = "game_toybox/game_toybox_sound/";

    CinemachineDollyCart kl_ccdc;
    Vector3 klStayPos;

    public override void OnStart(System.Action<bool> callback)
    {
        Debug.Log("--------------- DinosaurPkGame OnStart!");
        base.OnStart(callback);
        ResetData();
        CreateGameRoot();
        klStayPos = new Vector3(105.18f, -4.13f,13.24f);//(95.56f, -4.123f, 31.116f);
        AudioManager.Instance.PlayMusic("game_toybox/game_toybox_sound/601010210", true);

        SetDestination(new Vector3(0, 0, 0), () =>
        {
            Agent.enabled = false;
            actor.TurnFront(() =>
            {
                actor.PlayAnimator("idell_p", 0.1f, true);
            });
            kl_ccdc.enabled = true;
            kl_animator.CrossFade("run", 0.2f);
            kl_ccdc.m_Speed = 120;
            AudioManager.Instance.PlaySound(SOUND_PATH + "602030306", true, true);
        });
    }



    public override void OnUpdate()
    {
        //Debug.Log("  gameStart   1111 === " + gameStart);
        base.OnUpdate();
        if (kl_ccdc != null && kl_ccdc.m_Speed != 0)
        {
            //3.恐龙从左侧屏幕跑进场景中，从乐迪右侧绕后，最后停留在乐迪左侧，伴有吼叫音效
            if (Vector3.Distance(klStayPos, kl_ccdc.transform.position) < 0.5f)
            {
                Debug.Log("1111111 ==== ");
                kl_ccdc.m_Speed = 0;
                kl_ccdc.enabled = false;
                Debug.Log("  恐龙吼叫一声，动作展示  ===============   ");
                float len = AudioManager.Instance.PlaySound(SOUND_PATH + "602030401").Length;
                kl_animator.CrossFade("runaway", 0.2f);
                this.AddTimerEx(len, () => {
                    if (isEnd) return;
                    kl_animator.CrossFade("idell", 0.2f);
                    kl_ccdc.transform.localPosition = klStayPos;            
                });
                StartGame();
            }

        }
        //Test
        if (Input.GetKeyDown(KeyCode.Alpha0))
            Fighting(0);
        else if(Input.GetKeyDown(KeyCode.Alpha1))
            Fighting(1);
    }
    void StartGame()
    {
        lediClip_401010331 = AudioManager.Instance.GetAudioClip(SOUND_PATH + "401010331");
        AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SOUND_PATH + "602030306"));
        
        lediTransform.DORotate(new Vector3(0, 90, 0), 0.3f).OnComplete(() =>
        {
            PlayAnimator("jump_backward_p", 0.2f, false);
            lediTransform.DOMove(new Vector3(-75.8f, -5.389f, 13.3f), 0.533f).SetEase(Ease.Linear).OnComplete(() =>
            {
                //4.乐迪向后跳一步，摆出戒备姿态，说：“霸王龙号，这里是控制台，不许你乱来！”
                PlayAnimator("alert_talk_p", 0.2f, true);
                float length = AudioManager.Instance.PlaySound(SOUND_PATH + "401010327").Length;
                this.AddTimerEx(length + 0.5f, () =>
                {
                    PlayAnimator("idell_alert_p", 0.2f, true);
                    //5.恐龙吼叫一声，动作展示  (runaway)
                    Debug.Log("  5.恐龙吼叫一声，动作展示  ===============   ");
                    //float len = AudioManager.Instance.PlaySound(SOUND_PATH + "602030401").Length;
                    //kl_animator.CrossFade("runaway", 0.2f);
                    //this.AddTimerEx(len, () =>
                    //{
                        //kl_animator.CrossFade("idell", 0.2f);
                        //6.乐迪说：“请点击旁边的按钮，帮我加油助威，在你的帮助下我肯定能击败霸王龙号的！”
                        PlaySoundAnim("401010328", "alert_talk_p", 0.2f, true, () =>
                        {
                            if (isEnd) return;
                            //8.等乐迪说完话就开始进入pk，两人向前冲并碰撞到一起 
                            Debug.Log(" 8.等乐迪说完话就开始进入pk，两人向前冲并碰撞到一起   ");
                            kl_animator.CrossFade("run", 0.2f);
                            kl_ccdc.transform.DOMove(new Vector3(59.3f, -4.13f, 29.5f), 0.5f).OnComplete(() =>
                            {
                                if (isEnd) return;
                                kl_animator.CrossFade("wrestling", 0.2f);
                            });
                            PlayAnimator("walk_p", 0.2f, true);
                            lediTransform.DOMove(new Vector3(-34f, -5.389f, 13.3f), 0.5f).OnComplete(() =>
                            {
                                if (isEnd) return;
                                PlayAnimator("wrestling", 0.2f, true);
                                Debug.Log(" 9 开始PK ==== ");
                                DinosaurPkWindow.Instance.isFight = true;
                                if (!AudioManager.Instance.IsPlayingSoundClip(lediClip_401010331))
                                    AudioManager.Instance.PlaySound(lediClip_401010331, true);
                            });
                        },false);
                        this.AddTimerEx(0.2f, () =>
                        {
                            //7.展示PK进度条，两种颜色各占一半                               
                            WindowManager.Instance.OpenWindow(WinNames.DinosaurPkPanel);
                            //DinosaurPkWindow.Instance.backMain_Action = GameEnd;
                            DinosaurPkWindow.Instance.Fight_Action = Fighting;
                        });
                    //});
                });
            });
        });
    }
    GameObject go;
    Animator kl_animator;
    AudioClip lediClip_401010331;
    private void CreateGameRoot()
    {

        go = Res.LoadObj(ASSET_PATH);
        if (go != null)
        {
            go.transform.SetParent(toyboxGameRoot);
            kl_ccdc = go.transform.Find("kl_obj").GetComponent<CinemachineDollyCart>();
            kl_ccdc.m_Speed = 0;
            kl_animator = kl_ccdc.GetComponent<Animator>();
        }
    }
    float lastValue = 0.5f;
    bool isEnd = false;
    void Fighting(float value)
    {
        if (isEnd) return;
        if (value == -1f) {
            //AudioManager.Instance.GetAudioClip(SOUND_PATH + "401010328");
            AudioManager.Instance.StopAllSound();
            Close();
            return;
        }
        Debug.Log("  Fighting ===== " + value);
        if (value == 0)
        {
            isEnd = true;
            AudioManager.Instance.StopSound(lediClip_401010331);
            //my win 1)乐迪把恐龙摔出去，或顶到后面，然后乐迪走到中间面对镜头说：“谢谢你帮我一起制服了霸王龙号！”
            //2)说话的时候有称赞动作，循环动作
            // ledi pushwin  kl cast 
            animator.CrossFade("push_win", 0.2f);            
            kl_animator.CrossFade("crash", 0.2f);
            kl_animator.transform.DOMove(new Vector3(146.6f, -4.123f, 31.1f), 0.5f);
            this.AddTimerEx(1.5f, () =>
            {
                lediTransform.DORotate(new Vector3(0, 0, 0), 0.5f).OnComplete(() =>
                {
                    animator.CrossFade("all_praise_p_1", 0.2f);
                    var length = AudioManager.Instance.PlaySound(SOUND_PATH + "401010329").Length;
                    this.AddTimerEx(length, () =>
                    {
                        GameEnd();
                    });
                });
            });
        }
        else if (value >= 0.96f)
        {
            isEnd = true;
            AudioManager.Instance.StopSound(lediClip_401010331);
            //kl win 1)乐迪被恐龙摔出去，或顶到后面，乐迪摔倒，然后恐龙绕场一圈离开，然后乐迪站起来走到中间，面对镜头说：“这次太可惜了！下次一定能制服霸王龙号！”
            //2)说话的时候有懊恼动作，循环动作
            // ledi cast  push_win
            animator.CrossFade("cast", 0.2f);
            lediTransform.DOMove(new Vector3(-123.5f, -5.389f, 13.3f), 0.5f);
            this.AddTimerEx(0.6f, () =>
            {
                animator.CrossFade("idell_fall", 0.2f);
            });
            kl_animator.CrossFade("push_win", 0.2f);
            this.AddTimerEx(1.5f, () =>
            {
                //恐龙离开
                kl_animator.transform.DORotate(new Vector3(0, 90f, 0), 0.5f).OnComplete(() =>
                {
                    kl_animator.CrossFade("run", 0.2f);
                    kl_animator.transform.DOMoveX(375.5f, 3f).OnComplete(() => {                        
                    });
                });
                this.AddTimerEx(0.3f, () => {
                    animator.CrossFade("stand_up", 0.2f);
                    this.AddTimerEx(1.333f, () =>
                    {
                        lediTransform.DORotate(new Vector3(0, 0, 0), 0.5f).OnComplete(() =>
                        {
                            PlayLeDiVoiceAnimation("401010330", "all_unknow_0", () =>
                            {
                                GameEnd();
                            });
                        });
                    });
                });
            });           
        }
        else
        {
            if (value < lastValue)
            {
                //乐迪攻击  ledi push  恐龙 bepush  
                Debug.Log("  乐迪攻击 === ");
                PushAnim("ledi", "push_1");
                BePushedAnim("kl_animator", "be_pushed_1");
            }
            else if (value == lastValue)
            {
                //僵持  wrestling  
                Debug.Log("  僵持 === ");
                PushAnim("ledi", "wrestling");
                PushAnim("kl_animator", "wrestling");
            }
            else
            {
                //恐龙攻击   ledi bepush  恐龙 push
                Debug.Log("  恐龙攻击 === ");
                PushAnim("kl_animator", "push_1");
                BePushedAnim("ledi", "be_pushed_1");
            }
            lastValue = value;
        }
    }

    void Close()
    {
        Debug.Log("  Close ==== ");
 
        isEnd = true;
        AudioManager.Instance.StopSound(lediClip_401010331);
        WindowManager.Instance.CloseWindow(WinNames.DinosaurPkPanel);
        //kl win 1)乐迪被恐龙摔出去，或顶到后面，乐迪摔倒，然后恐龙绕场一圈离开，然后乐迪站起来走到中间，面对镜头说：“这次太可惜了！下次一定能制服霸王龙号！”
        //2)说话的时候有懊恼动作，循环动作
        // ledi cast  push_win
        if (DinosaurPkWindow.Instance.isFight)
        {
            DinosaurPkWindow.Instance.isFight = false;
            animator.CrossFade("cast", 0.2f);
            lediTransform.DOMove(new Vector3(-123.5f, -5.389f, 13.3f), 0.5f);
            this.AddTimerEx(0.6f, () =>
            {
                animator.CrossFade("idell_fall", 0.2f);
            });
            kl_animator.CrossFade("push_win", 0.2f);
            this.AddTimerEx(1.5f, () =>
            {
                //恐龙离开
                kl_animator.transform.DORotate(new Vector3(0, 90f, 0), 0.5f).OnComplete(() =>
                    {
                        kl_animator.CrossFade("run", 0.2f);
                        kl_animator.transform.DOMoveX(375.5f, 3f).OnComplete(() =>
                        {
                        });
                    });
                this.AddTimerEx(0.3f, () =>
                {
                    animator.CrossFade("stand_up", 0.2f);
                    this.AddTimerEx(1.333f, () =>
                    {
                        lediTransform.DORotate(new Vector3(0, 0, 0), 0.5f).OnComplete(() =>
                        {
                            PlayLeDiVoiceAnimation("401010330", "all_unknow_0", () =>
                            {
                                GameEnd();
                            });
                        });
                    });
                });
            });
        }
        else
        {
            animator.CrossFade("idell_p", 0.2f);
            //恐龙离开
            kl_animator.transform.DORotate(new Vector3(0, 90f, 0), 0.3f).OnComplete(() =>
            {
                kl_animator.CrossFade("run", 0.2f);
                kl_animator.transform.DOMoveX(375.5f, 1f).OnComplete(() =>
                {
                    GameEnd();
                });
            });
           
        }
    }

    void PushAnim(string player, string name)
    {
        Animator anim = null;
        if (player == "ledi")
            anim = animator;
        else
            anim = kl_animator;
        AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
        //Debug.LogError("player === "+ player +" , currentName === "+anim.GetCurrentAnimatorClipInfo(0)[0].clip.name +"    ,name === "+name+" ,  "+ (info.IsName("pushed_1") || info.IsName("pushed_2") || info.IsName("be_pushed_1") || info.IsName("be_pushed_2")).ToString());
        if (info.IsName("push_1") || info.IsName("push_2"))
            return;
        else
            anim.CrossFade(name, 0.2f);
    }
    void BePushedAnim(string player, string name)
    {
        Animator anim = null;
        if (player == "ledi")
            anim = animator;
        else
            anim = kl_animator;
        AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
        //Debug.LogError("player === " + player + " , currentName === " + anim.GetCurrentAnimatorClipInfo(0)[0].clip.name + "    ,name === " + name + " ,  " + (info.IsName("pushed_1") || info.IsName("pushed_2") || info.IsName("be_pushed_1") || info.IsName("be_pushed_2")).ToString());
        if (info.IsName("be_pushed_1") || info.IsName("be_pushed_2"))
            return;
        else
            anim.CrossFade(name, 0.2f);
    }
    /// <summary>
    /// 游戏结束
    /// </summary>
    public void GameEnd()
    {
        DinosaurPkWindow.Instance.isFight = false;
        base.Agent.enabled = true;
        if (go != null)
        {
            Debug.Log(" OnExit ");
            GameObject.Destroy(go);
            go = null;
        }
        WindowManager.Instance.CloseWindow(WinNames.DinosaurPkPanel);
        AudioManager.Instance.PlayMusic("sound_bg/601010101",true);
        OnGameComplete(true);
    }
    public override void OnExit()
    {
        base.OnExit();
    }

    public void ResetData()
    {
        isEnd = false;
    }

    private void PlaySoundAnim(string voicePath, string animName, float fade, bool isLoop, System.Action callback = null, bool isChangeIdel = true)
    {
        AudioClip clip = AudioManager.Instance.GetAudioClip(SOUND_PATH + voicePath);
        if (AudioManager.Instance.IsPlayingSoundClip(clip)) return;
        var length = AudioManager.Instance.PlaySound(SOUND_PATH + voicePath).Length;
        PlayAnimator(animName, fade, isLoop);
        this.AddTimerEx(length, () =>
        {
            if (isChangeIdel)
            {
                PlayAnimator("idell_alert_p", fade, true);
                Debug.Log("  PlaySoundAnim  idell_p ");
            }
            if (callback != null)
                callback();
        });
    }

    private bool isPlayingLdAniSound = false;
    public void PlayLeDiVoiceAnimation(string voicePath, string actName, System.Action act = null)
    {
        AudioClip clip = AudioManager.Instance.GetAudioClip(SOUND_PATH + voicePath);
        if (isPlayingLdAniSound)
        {
            return;
        }
        isPlayingLdAniSound = true;
        PlayAnimator(actName + "1", 0.2f, false);
        this.AddTimerEx(0.5f, () =>
        {
            var length = AudioManager.Instance.PlaySound(SOUND_PATH + voicePath).Length;
            PlayAnimator(actName + "2", 0f, true);
            this.AddTimerEx(length, () =>
            {
                PlayAnimator(actName + "3", 0f, false);
                if (act != null)
                    act();

                isPlayingLdAniSound = false;
            });
        });
    }

}
